<template>
  <div class="login-container">
   <el-card class="box-card">
     <div class="login-title"></div>
     <el-form ref="form" :model="userInfo" :rules="rules">
       <el-form-item prop="username">
       <el-input placeholder="请输入用户名" prefix-icon="el-icon-user" v-model="userInfo.username"></el-input>
       </el-form-item>
       <el-form-item prop="password">
       <el-input placeholder="请输入密码" prefix-icon="el-icon-lock" type="password" show-password v-model="userInfo.password"></el-input>
       </el-form-item>
       <el-form-item prop="repassword">
       <el-input placeholder="请确认密码" prefix-icon="el-icon-lock" type="password" show-password v-model="userInfo.repassword"></el-input>
       </el-form-item>
       <el-button @click="reg">注册</el-button>
     </el-form>
     <el-link :underline="false" @click="$router.push('/login')">已有账号，去登录</el-link>
   </el-card>
  </div>
</template>
<script>
import { regApi } from '../api/reg.js'

export default {
  data() {
    var validatePass2 = (rule, value, callback) => {
      // rule 没什么用。
      // value 表示使用这个规则的输入框。案例中，确认密码使用这个验证规则，所以value表示我们输入的确认密码值
      // callback 表示是否通过验证

      // 和密码进行比较
      if (value !== this.userInfo.password) { // 这里的this.userInfo.password表示我们的密码
        callback(new Error('两次输入密码不一致!')) // 验证不通过，传入错误对象
      } else {
        callback() // 验证通过，直接callback()
      }
    }
    return {
      userInfo: {
        username: '',
        password: '',
        repassword: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9]{1,10}$/, message: '用户名长度1-10位', trigger: 'blur' }
          // { required: true, message: '请输入用户名', trigger: 'blur' },
          // { pattern: /^[a-zA-Z0-9]{1,10}$/, message: '密码长度6-15位', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9]{6,15}$/, message: '密码长度6-15位', trigger: 'blur' }],
        repassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9]{6,15}$/, message: '密码长度6-15位', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' }]
      }
    }
  },
  methods: {
    reg() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        const { data: res } = await regApi(this.userInfo)
        if (res.code === 0) {
          this.$message.success(res.message)
        } else {
          this.message({ type: 'error', message: res.message })
        }
      })
    }
  }

}
</script>

<style>
.login-container {
  height: 100%;
  background: url(../assets/images/login_bg.jpg) no-repeat;
  background-size: cover;
}
.el-card {
  width: 400px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%)
}
.login-title {
  height: 60px;
  background: url(../assets/images/login_title.png) 50% no-repeat;
}
.el-button {
  width: 100%;
}

</style>
